// kit-qr 从标准输入或命令行接收信息生成二维码
package main

import (
	"bufio"
	"flag"
	"fmt"
	"image/gif"
	"image/jpeg"
	"image/png"
	"os"
	"path"
	"strings"

	"gitee.com/xuender/kits/cmd"
	"gitee.com/xuender/kits/gifs"
	"gitee.com/xuender/kits/svgs"
	"gitee.com/xuender/oils/base"
	"gitee.com/xuender/oils/logs"
	svg "github.com/ajstarks/svgo"
	"github.com/boombuler/barcode"
	"github.com/boombuler/barcode/qr"
)

const (
	width = 200
	size  = 5
)

// nolint: gochecknoglobals
var (
	cliFile      string
	cliType      string
	cliWidth     int
	cliBlockSize int
)

func input() string {
	var str string

	if flag.NArg() == 0 {
		// 标准输入
		s := bufio.NewScanner(os.Stdin)
		list := []string{}

		for s.Scan() {
			list = append(list, s.Text())
		}

		str = strings.Join(list, "\n")
	} else {
		// 命令行
		list := make([]string, flag.NArg())

		for i := 0; i < flag.NArg(); i++ {
			list[i] = flag.Arg(i)
		}

		str = strings.Join(list, " ")
	}

	return str
}

func main() {
	str := input()
	ext := path.Ext(cliFile)

	if ext == "" {
		ext = cliType
		cliFile = cliFile + "." + cliType
	} else {
		ext = ext[1:]
	}

	logs.Info("file =", cliFile)
	logs.Info("ext =", ext)
	logs.Info("str =", str)
	qrCode, err := qr.Encode(str, qr.M, qr.Auto)
	base.Panic(err)
	file, err := os.Create(cliFile)
	base.Panic(err)

	defer file.Close()

	if strings.EqualFold(ext, "svg") {
		image := svg.New(file)
		qs := svgs.NewQrSVG(qrCode, cliBlockSize)

		qs.StartQrSVG(image)
		base.Panic(qs.WriteQrSVG(image))
		image.End()

		return
	}

	code, err := barcode.Scale(qrCode, cliWidth, cliWidth)
	base.Panic(err)

	if strings.EqualFold(ext, "png") {
		base.Panic(png.Encode(file, code))

		return
	}

	if strings.EqualFold(ext, "gif") {
		colors := 2

		base.Panic(gif.Encode(file, code, &gif.Options{NumColors: colors, Quantizer: &gifs.BwQuantizer{}}))

		return
	}

	if strings.EqualFold(ext, "jpeg") || strings.EqualFold(ext, "jpg") {
		size := 50

		base.Panic(jpeg.Encode(file, code, &jpeg.Options{Quality: size}))

		return
	}
}

// nolint: gochecknoinits
func init() {
	flag.Usage = usage
	flag.StringVar(&cliFile, "o", "qr", "output file name")
	flag.StringVar(&cliType, "t", "png", "file type[png,svg,gif,jpeg]")
	flag.IntVar(&cliWidth, "w", width, "qr width")
	flag.IntVar(&cliBlockSize, "b", size, "svg qr block Size")

	flag.Parse()
}

func usage() {
	fmt.Fprintf(flag.CommandLine.Output(), "kit-qr [%s]\n\n", cmd.ModVersion)
	fmt.Fprintf(flag.CommandLine.Output(), "生成二维码\n\n")
	fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", os.Args[0])
	flag.PrintDefaults()
	fmt.Fprintf(flag.CommandLine.Output(), "\n模块: %s\n提交: %s\n", cmd.ModPath, cmd.ModSum)
}
